﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Web.Configuration;
using System.Data.SqlClient;

namespace Perm.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class LoadHouses
    {
       string selectMSSQL = "", String = "",
               error = null;
        double startX, startY,
               X, Y, kooficientMIN = 1.5, kooficientMAX = 1000.0;
        int id = 0, no = 0;

        SqlConnection conMSSQL;
        SqlDataReader readerMSSQL;
        SqlCommand commandMSSQL;

        DateTime thisDate = DateTime.Now.ToUniversalTime().AddHours(6);

        List<House> houseList = new List<House>();
        House house = new House();
        int i = 0;
        [OperationContract]
        public List<House> DoWork(string city)
        {
            string connectionStringMSSQL = WebConfigurationManager.ConnectionStrings["MSSQL"].ConnectionString;

            try
            {
                conMSSQL = new SqlConnection(connectionStringMSSQL);
                conMSSQL.Open();
            }
            catch { error += " Невозможно подключиться к базе данных. MS SQL (LoadRoads)"; }

            switch (city)
            {
                case "perm":
                    {
                        //Запрос на постройки
                        selectMSSQL = "SELECT [NO], POINT_XCOORD, POINT_YCOORD, [INDEX], EDGEITEM_XCOORD, EDGEITEM_YCOORD FROM HOME_PERM2 ORDER BY NO, [INDEX]";                        
                        //selectMSSQL = "SELECT RIVER_PERM.[NO], RIVER_PERM.POINT_XCOORD, RIVER_PERM.POINT_YCOORD, RIVER_PERM.[INDEX], RIVER_PERM.EDGEITEM_XCOORD, RIVER_PERM.EDGEITEM_YCOORD FROM RIVER_PERM ORDER BY NO, [INDEX]";                        
                        //Запрос на реки
                        //selectMSSQL = "SELECT [NO], x, y, [INDEX], XCOORD, YCOORD FROM RIVER_PERM ORDER BY NO, [INDEX]";
                        //Запрос на зелень
                        //selectMSSQL = "SELECT [NO], x, y, [INDEX], XCOORD, YCOORD FROM GREEN_PERM ORDER BY NO, [INDEX]";                        
                        break;
                    }
                case "ekb":
                    {
                        selectMSSQL = "SELECT HOME_EKB.[NO], HOME_EKB.POINT_XCOORD, HOME_EKB.POINT_YCOORD, HOME_EKB.[INDEX], HOME_EKB.EDGEITEM_XCOORD, HOME_EKB.EDGEITEM_YCOORD FROM HOME_EKB ORDER BY NO, POINT_XCOORD";                        
                        break;
                    }
                case "permkray":
                    {
                        //selectMSSQL = "SELECT HOME_PERMKRAY.[NO], HOME_PERMKRAY.POINT_XCOORD, HOME_PERMKRAY.POINT_YCOORD, HOME_PERMKRAY.[INDEX], HOME_PERMKRAY.EDGEITEM_XCOORD, HOME_PERMKRAY.EDGEITEM_YCOORD FROM HOME_PERMKRAY ORDER BY NO, [INDEX]";                                               
                        break;
                    }
            }
            try
            {
                commandMSSQL = new SqlCommand(selectMSSQL, conMSSQL);
                readerMSSQL = commandMSSQL.ExecuteReader();
            }
            catch { error += "Невозможно считать данный из базы. MSSQL. "; }

            string no = "";
            readerMSSQL.Read();
            startClass();
            while (readerMSSQL.Read())
            {
                if (readerMSSQL[3].ToString() != "1")
                {
                    addNoXY();
                    while (readerMSSQL.Read())
                    {
                        if (readerMSSQL.GetInt32(0) != house.id)
                        {
                            no = readerMSSQL[3].ToString();
                            houseList.Add(house); startClass();
                            break;
                        }
                        else
                        {
                            if (readerMSSQL[3].ToString() != house.no.Split(';')[house.no.Split(';').Length - 2])
                            {
                                addNoXY();
                            }
                            else i++;
                        }
                    }
                }
                else i++;
            }
            #region old
            /*
            readerMSSQL.Read();
            m1:
                house = new House();
                id = readerMSSQL.GetInt32(0);
            
                startX = Math.Round(readerMSSQL.GetDouble(1), 2);
                startY = Math.Round(readerMSSQL.GetDouble(2), 2);

                house.id = id;
                house.X += startX + ";";
                house.Y += startY + ";";

                if ((Math.Abs(startX - X) > kooficientMIN || Math.Abs(startY - Y) > kooficientMIN))
                {
                    X = Math.Round(readerMSSQL.GetDouble(4), 2);
                    Y = Math.Round(readerMSSQL.GetDouble(5), 2);
                    house.X += X + ";";
                    house.Y += Y + ";";
                }

                while (readerMSSQL.Read())
                {
                    if (readerMSSQL.GetInt32(0) == id)
                    {
                        no = readerMSSQL.GetInt32(3);
                        double raznicaX = Math.Abs(Math.Round(readerMSSQL.GetDouble(4), 2) - X);
                        double razniczY = Math.Abs(Math.Round(readerMSSQL.GetDouble(5), 2) - Y);
                        if ((raznicaX > kooficientMIN || razniczY > kooficientMIN))
                        {
                            X = Math.Round(readerMSSQL.GetDouble(4), 2);
                            Y = Math.Round(readerMSSQL.GetDouble(5), 2);
                            house.X += X + ";";
                            house.Y += Y + ";";
                        }
                    }
                    else
                    {
                        HouseList.Add(house);
                        goto m1;
                    }
                }
             */
            #endregion
            return houseList;
        }
        /// <summary>
        /// Добавляем класс и записываем в него нулевую и первую точку
        /// </summary>
        void startClass()
        {
            house = new House();
            house.id = readerMSSQL.GetInt32(0);
            house.no += readerMSSQL[3].ToString() + ";";
            house.X = readerMSSQL[1].ToString() + ";" + readerMSSQL[4].ToString() + ";";
            house.Y = readerMSSQL[2].ToString() + ";" + readerMSSQL[5].ToString() + ";";
        }
        /// <summary>
        /// Добавление точки и её номера в класс.
        /// </summary>
        void addNoXY()
        {
            house.no += readerMSSQL[3].ToString() + ";";
            house.X += readerMSSQL[4].ToString() + ";";
            house.Y += readerMSSQL[5].ToString() + ";";
        }
        [DataContract]
        public class House
        {
            [DataMember]
            public int id = 0;
            [DataMember]
            public string no = "0;";
            [DataMember]
            public string X = "";
            [DataMember]
            public string Y = "";
        }

        // Add more operations here and mark them with [OperationContract]
    }
}
